package cn.tedu.csmall.product.webapi.service;

import cn.tedu.csmall.commons.exception.ServiceException;
import cn.tedu.csmall.commons.response.ServiceCode;
import cn.tedu.csmall.pojo.dto.AlbumAddNewDTO;
import cn.tedu.csmall.pojo.entity.Album;
import cn.tedu.csmall.pojo.vo.AlbumStandardVO;
import cn.tedu.csmall.product.service.IAlbumService;
import cn.tedu.csmall.product.webapi.mapper.AlbumMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static cn.tedu.csmall.commons.response.ServiceCode.*;

@Service
@Slf4j
public class AlbumServiceImp implements IAlbumService {

    @Autowired
    private AlbumMapper mapper;


    /**
     * 增加相册业务
     * @param albumAddNewDTO 封装的相册数据
     * @return
     */
    @Override
    public Long addNew(AlbumAddNewDTO albumAddNewDTO) {
        String name = albumAddNewDTO.getName();
        //查找是否有该相册
        AlbumStandardVO queryNameResult = mapper.getByName(name);
        if (queryNameResult != null) {
            log.warn("增加相册失败，该相册[{}]已存在",name);
            throw new ServiceException(CONFLICT,"增加相册失败，该相册已存在");
        }
        //添加相册默认属性
        Album album = new Album();
        BeanUtils.copyProperties(albumAddNewDTO,album);
        LocalDateTime now =  LocalDateTime.now();
        album.setGmtCreate(now);
        album.setGmtModified(now);
        int row = mapper.insert(album);
        if (row != 1){
            log.warn("增加相册失败，服务器忙，请稍后再次尝试！");
            throw new ServiceException(INTERNAL_SERVER_ERROR,"增加相册失败，服务器忙，请稍后再次尝试！");
        }
        log.debug("增加相册，完成，将返回新增的类别的id：{}", album.getId());
        return album.getId();
    }
}
